package com.bdcom.autotest.telnet.invoke.impl;

import com.bdcom.autotest.telnet.TelnetClientForCOM;
import com.bdcom.autotest.telnet.TelnetCommunication;
import com.bdcom.autotest.telnet.constant.TelnetConstant;
import com.bdcom.autotest.telnet.invoke.DeveiceOper;
import com.bdcom.autotest.telnet.model.DevIPObj;
import com.bdcom.autotest.telnet.model.Result;
import com.bdcom.autotest.telnet.model.TelnetCMDObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class DevIPSet implements DeveiceOper, TelnetConstant {
    private static final Logger logger = LoggerFactory.getLogger(DevIPSet.class);
    @Override
    public Result executeCMD(TelnetCMDObj obj) {
        String cmd="";
        String wantPingIP="";
        String setIP="";
        if(obj instanceof DevIPObj){
            cmd=((DevIPObj) obj).buildCMD();
            wantPingIP=((DevIPObj) obj).getWantPingIP();
            setIP=((DevIPObj) obj).getIpAdd();
        }
        Result result=new Result();
        TelnetClientForCOM clientForCOM=null;
        try {
            TelnetCommunication communication=new TelnetCommunication();
            clientForCOM=new TelnetClientForCOM(obj.getIp(),obj.getPort());
            Result loginResult=communication.login(obj.getUser(),obj.getPassword(),clientForCOM,obj.isMonitor());
            if(loginResult.getStatus()){
                Result enableResult = communication.enableOper(clientForCOM, obj.getEnablePassword(),obj.isMonitor());
                if(enableResult.getStatus()){
                    boolean flag = communication.sendSetIP(clientForCOM, cmd);
                    if(flag){
                        //成功后需要ping tftp服务器验证
                        Thread.sleep(5000);//延迟5s再ping
                        result=communication.sendPing(clientForCOM,wantPingIP,setIP);

                    }else{
                        result.setStatus(false);
                        result.setFailedReason("timeout");
                    }

                    return result;

                }else{
                    return enableResult;
                }
            }else{
                return loginResult;
            }
            

        }catch (Exception e){
            result.setFailedReason(e.toString());
            return result;
        }finally {
            if(null!=clientForCOM){
                try {

                    if(!obj.isMonitor()){
                        //非monitor模式下恢复telnet连接的COM口的初始状态
                        clientForCOM.sendCommand("exit",200L);
                        clientForCOM.sendCommand("exit",200L);
                    }

                    clientForCOM.disConnect();
                } catch (Exception e) {
                    logger.error(e.toString());
                }
            }
        }


    }
    public Result setIPMask(DevIPObj obj){
        obj.setMonitor(true);
        Result result = executeCMD(obj);
        return result;


    }
}
